package cn.lina.middleware.dynamic.thread.pool.sdk.registry.redis;

import cn.lina.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.lina.middleware.dynamic.thread.pool.sdk.domain.model.valobj.RegistryEnumVO;
import cn.lina.middleware.dynamic.thread.pool.sdk.registry.IRegistry;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.List;

/**
 * @author 24449
 * @date 2025/8/13
 * @description Redis注册中心
 */
public class RedisRegistry implements IRegistry {

    private final RedissonClient redissonClient;

    public RedisRegistry(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 上报线程池信息
     * @param threadPoolEntities
     */
    @Override
    public void reportThreadPool(List<ThreadPoolConfigEntity> threadPoolEntities) {
        RList<Object> list = redissonClient.getList(RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey());
        // 删除之后直接覆盖添加
        list.delete();
        list.addAll(threadPoolEntities);
    }

    /**
     * 上报线程池配置参数
     * @param threadPoolConfigEntity
     */
    @Override
    public void reportThreadPoolConfigParameter(ThreadPoolConfigEntity threadPoolConfigEntity) {
        // 获取唯一的key
        String cacheKey = RegistryEnumVO.THREAD_POOL_CONFIG_PARAMETER_LIST_KEY.getKey() + "_" + threadPoolConfigEntity.getAppName() + "_" + threadPoolConfigEntity.getThreadPoolName();
        // redissonClient.getBucket(cacheKey) 它用于获取一个 Redisson 的分布式对象，
        // 这个对象在 Redis 中对应于一个简单的键值对（Key-Value）。
        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(cacheKey);
        bucket.set(threadPoolConfigEntity, Duration.ofDays(30));
    }
}
